import {ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit} from '@angular/core';
import {FormArray, FormBuilder, FormGroup} from "@angular/forms";
import {NzMessageService} from "ng-zorro-antd/message";
import {ValidatorsService} from "../../../../core/services/validators/validators.service";
import {MsdsIdService} from "../../../../core/services/store/biz-store-service/msds-id/msds-id.service";
import {fnCheckForm} from "../../../../utils/tools";
import {MsdsLawHttpService} from "../../../../core/services/http/msds/msds-law.service";
import {AdminService} from "../../../../core/services/store/admin.service";


@Component({
  selector: 'app-msds-law',
  templateUrl: './msds-law.component.html',
  styleUrls: ['./msds-law.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MsdsLawComponent implements OnInit {
  validateForm!: FormGroup;
  formOrder = 1;
  msdsEntprId!: number;
  isAdd = false;
  id!: number;

  constructor(private fb: FormBuilder, private msg: NzMessageService,
              private validatorsService: ValidatorsService,
              private cdr: ChangeDetectorRef,
              private msdsIdService: MsdsIdService, public AdminService: AdminService,
              private dataService: MsdsLawHttpService) {
  }

  get valuesArray(): FormArray {
    return this.validateForm.controls['lawDetailList'] as FormArray;
  }

  add(): void {
    this.valuesArray.push(this.creatForm());
  }

  del(index: number): void {
    this.valuesArray.removeAt(index);
  }

  creatForm(): FormGroup {
    return this.fb.group({
      lawDetail: [null],
      remark: [null],
    })
  }

  initForm(): void {
    this.validateForm = this.fb.group({
      law: ['下列法律法规和标准，对化学品的安全使用、储存、运输、装卸、分类和标志等方面均作了相应的规定'],
      lawDetailList: this.fb.array([
        this.creatForm()
      ]),

    });
  }

  submitForm(): void {
    if (!fnCheckForm(this.validateForm)) {
      return;
    }
    const params = this.validateForm.value;
    if (this.isAdd) {
      params.msdsEntprId = this.msdsEntprId;
      this.dataService.addMsdsLaw(params).subscribe(res => {
        this.id = res;
        this.isAdd = false;
      });
    } else {
      params.id = this.id;
      this.dataService.editMsdsLaw(params).subscribe()
    }
  }

  getDetail(msdsEntprId: number): void {
    this.dataService.getMsdsLawDetail(msdsEntprId).subscribe(res => {
      this.isAdd = !res;
      if (!!res) {
        if (res.lawDetailList && res.lawDetailList.length > 1) {
          for (let i = 0; i < res.lawDetailList.length - 1; i++) {
            this.add();
          }
        }
        this.id = res.id as number;
        this.validateForm.patchValue(res);
      }
    })
  }


  ngOnInit(): void {
    this.initForm();
    this.msdsIdService.getMsdsIdStoreStore().subscribe(res => this.msdsEntprId = res);
    this.getDetail(this.msdsEntprId);
  }

}

